package com.example.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.domain.User;
import com.example.enums.ResultCodeEnum;
import com.example.exception.CustomException;
import com.example.mapper.UserMapper;
import com.example.service.UserService;
import com.example.utils.JwtTokenUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import static com.example.enums.ResultCodeEnum.USER_NOT_EXIST_ERROR;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Resource
    private UserMapper userMapper;

    @Override
    public String login(User user) {
        User dbUser = userMapper.selectOne(new LambdaQueryWrapper<User>()
                .eq(User::getUsername, user.getUsername()));
        if (ObjectUtil.isNull(dbUser)) {
            throw new CustomException(USER_NOT_EXIST_ERROR);
        }

        if (!user.getPassword().equals(dbUser.getPassword())) {
            throw new CustomException(ResultCodeEnum.USER_ACCOUNT_ERROR);
        }

        // 生成token
        String token = JwtTokenUtils.createToken(String.valueOf(dbUser.getId()), dbUser.getPassword());
        return token;
    }
}
